package cn.sciento.websocket.helper;

import cn.sciento.core.exception.CommonException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.sciento.websocket.vo.MsgVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class SocketSendHelper {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    public void sendBySession(String sessionId, String key, String message) {
        MsgVO msg = (new MsgVO()).setSessionId(sessionId).setKey(key).setMessage(message).setType("S");
        try {
            this.redisTemplate.convertAndSend("stong-webSocket", this.objectMapper.writeValueAsString(msg));
        } catch (JsonProcessingException e) {
            throw new CommonException(e);
        }
    }

    public void sendByUserId(Long userId, String key, String message) {
        MsgVO msg = (new MsgVO()).setUserId(userId).setKey(key).setMessage(message).setType("U");
        try {
            this.redisTemplate.convertAndSend("stong-webSocket", this.objectMapper.writeValueAsString(msg));
        } catch (JsonProcessingException e) {
            throw new CommonException(e);
        }
    }

    public void sendToAll(String key, String message) {
        MsgVO msg = (new MsgVO()).setKey(key).setMessage(message).setType("A");
        try {
            this.redisTemplate.convertAndSend("stong-webSocket", this.objectMapper.writeValueAsString(msg));
        } catch (JsonProcessingException e) {
            throw new CommonException(e);
        }
    }
}
